package com.six.backend.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.six.backend.annotation.OperLog;
import com.six.backend.config.QiNiuCloudProperties;
import com.six.backend.pojo.*;
import com.six.backend.service.SourceMaterialService;
import com.six.backend.service.SummaryService;
import com.six.backend.service.UserService;
import com.six.backend.shiro.Utils.Result;
import com.six.backend.utils.QiNiuUtils;
import com.six.backend.utils.TokenUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: skyler
 * @Date: 2021/11/10 10:20
 */

@ResponseBody
@RestController
@Slf4j
@Transactional(rollbackFor=Exception.class)
@RequestMapping(value = "/SourceMaterial", produces = "application/json;charset = utf-8")
public class SourceMaterialController {
    @Autowired
    private SourceMaterialService sourceMaterialService;

    @Autowired
    private UserService userService;

    @Autowired
    private QiNiuCloudProperties qiNiuCloudProperties;

    @Autowired
    private SummaryService summaryService;

    @RequiresPermissions("datamanage:find:picturedata")
    @GetMapping("/getImageSourse")
    @ApiOperation("获取图片素材信息")
    @OperLog(operModule = "数据管理模块",operType = "get",operDesc = "获取图片素材信息操作")
    public Result getImgSourceMaterialByName(@RequestParam(value = "name",required = false) String name,
                                             @RequestParam(value = "pageSize") @NotNull(message = "pageSize不能为空") Integer pageSize,
                                             @RequestParam(value = "pageNum") @NotNull(message = "pageNum不能为空") Integer pageNum,
                                            HttpServletRequest request) {
        String account = TokenUtil.getTokenName(request);
        HashMap map = new HashMap<>();
        map.put("name",name);
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        List<SourceMaterial> list1 = sourceMaterialService.selectImgSourceMaterialByName(map,account);
        return new Result<>().setCode(200).setMessage("请求成功").setData(new PageInfo<>(list1));
    }

    @GetMapping("/getSourceMaterial")
    @RequiresPermissions("datamanage:find:document")
    @ApiOperation("获取文档素材信息")
    @OperLog(operModule = "数据管理模块",operType = "get",operDesc = "获取文档素材信息操作")
    public Result getDocuentSourceMaterialByName(@RequestParam(value = "name",required = false) String name,
                                                 @RequestParam(value = "pageSize") Integer pageSize,
                                                 @RequestParam(value = "pageNum") Integer pageNum) {
        HashMap map = new HashMap<>();
        map.put("name",name);
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        List<SourceMaterial> list1 = sourceMaterialService.selectDocumentSourceMaterialByName(map);
        return new Result<>().setCode(200).setMessage("请求成功").setData(new PageInfo<>(list1));
    }

    @DeleteMapping("/deleteSourceMaterial")
    @ApiOperation("删除素材资源")
    @OperLog(operModule = "数据管理模块",operType = "delete",operDesc = "删除素材信息操作")
    public Result deleteSourceMaterialByName(@RequestParam(value = "id") String id) throws FileNotFoundException {
        HashMap map = new HashMap<>();
        map.put("id",id);
        String status = sourceMaterialService.deleteDocumentByName(map,id);
        if ("true".equals(status)) {
            return new Result<>().setCode(200).setMessage("删除成功");
        }
        return new Result<>().setCode(401).setMessage("删除失败");
    }

    @PostMapping("/uploadSource")
    @ApiOperation("上传资源素材信息")
    @OperLog(operModule = "数据管理模块",operType = "post",operDesc = "上传素材资源操作")
    public Result uploadSourceMaterial(@RequestParam(required = false) MultipartFile file,
                                       @RequestParam(required = false) Integer conferenceId,
                                       @RequestParam(required = false) String auther,
                                       HttpServletRequest request) throws IOException {
        if (file == null) {
            return new Result<>().setCode(401).setMessage("上传失败");
        }
//        //获取上传文件用户的id
        String account = TokenUtil.getTokenName(request);
        User user = userService.selectUserBYId(account);
        SourceMaterial sourceMaterial = new SourceMaterial();
        sourceMaterial.setImportPeople(user.getName());
        if (conferenceId != null) {
            sourceMaterial.setBelongConferenceId(conferenceId);
        }else {
            sourceMaterial.setBelongConferenceId(-1);
        }
        if (auther != null) {
            sourceMaterial.setAuthor(auther);
        }
        // 存储空间的域名
        String domain = "http://skylery.walnute.top/";
        //获取文件名
        String key = QiNiuUtils.upload(qiNiuCloudProperties, file);
        // 返回文件在七牛云对象存储空间中的url
        String url =  domain+ key +"?attname="+file.getOriginalFilename();
        sourceMaterial.setId(key);
        sourceMaterial.setAddress(url);
        String id = sourceMaterialService.checkSource(key,conferenceId);
        if (id != null) {
            return new Result<>().setCode(403).setMessage("重复上传");
        }
        sourceMaterialService.save(sourceMaterial,file);
        return new Result<>().setCode(200).setMessage("上传成功").setData(url);
    }

    @PostMapping("/uploadSummary")
    @ApiOperation("上传会议纪要")
    @OperLog(operModule = "数据管理模块",operType = "post",operDesc = "上传会议纪要")
    public Result uploadSummary(@RequestParam(required = false) MultipartFile file,
                                       @RequestParam("conferenceId") Integer conferenceId,
                                       @RequestParam(required = false) String auther,
                                       HttpServletRequest request) throws IOException {
        if (file == null) {
            return new Result<>().setCode(401).setMessage("上传失败");
        }
        if (conferenceId == null) {
            return new Result<>().setCode(401).setMessage("请输入会议id");

        }
//        //获取上传文件用户的id
        String account = TokenUtil.getTokenName(request);
        User user = userService.selectUserBYId(account);
        SourceMaterial sourceMaterial = new SourceMaterial();
        sourceMaterial.setImportPeople(user.getName());
        sourceMaterial.setBelongConferenceId(conferenceId);
        if (auther != null) {
            sourceMaterial.setAuthor(auther);
        }
        // 存储空间的域名
        String domain = "http://skylery.walnute.top/";
        //获取文件名
        String key = QiNiuUtils.upload(qiNiuCloudProperties, file);
        // 返回文件在七牛云对象存储空间中的url
        String url =  domain+ key +"?attname="+file.getOriginalFilename();
        sourceMaterial.setId(key);
        sourceMaterial.setAddress(url);
        String id = sourceMaterialService.checkSource(key,conferenceId);
        Summary summary = new Summary();
        if (id != null) {
            summary.setMaterialId(id);
            summary.setBelongConferenceId(conferenceId);
            summary.setSummaryName(file.getOriginalFilename());
            summary.setSummaryWriterAccount(account);
            summary.setDocumentName(file.getOriginalFilename());
            summaryService.saveSummary(summary);
            return new Result<>().setCode(200).setMessage("上传成功");
        } else {
            String materialId =  sourceMaterialService.save(sourceMaterial,file);
            summary.setMaterialId(materialId);
            summary.setBelongConferenceId(conferenceId);
            summary.setSummaryName(file.getOriginalFilename());
            summary.setSummaryWriterAccount(account);
            summary.setDocumentName(file.getOriginalFilename());
            summaryService.saveSummary(summary);
            return new Result<>().setCode(200).setMessage("上传成功").setData(url);
        }
    }



    @PostMapping("/uploadConferenceSource")
    @ApiOperation("上传会议素材信息")
    @OperLog(operModule = "数据管理模块",operType = "post",operDesc = "上传会议素材操作")
    public Result uploadConferenceSouce(@RequestParam(required = false) MultipartFile file,
                                       @RequestParam("conferenceId") Integer conferenceId,
                                       @RequestParam(required = false) String auther,
                                       HttpServletRequest request) throws IOException {
        if (file == null) {
            return new Result<>().setCode(401).setMessage("上传失败");
        }
//        //获取上传文件用户的id
        String account = TokenUtil.getTokenName(request);
        User user = userService.selectUserBYId(account);
        SourceMaterial sourceMaterial = new SourceMaterial();
        sourceMaterial.setImportPeople(user.getName());
        sourceMaterial.setBelongConferenceId(conferenceId);
        if (auther != null) {
            sourceMaterial.setAuthor(auther);
        }
        // 存储空间的域名
        String domain = "http://skylery.walnute.top/";
        //获取文件名
        String key = QiNiuUtils.upload(qiNiuCloudProperties, file);
        // 返回文件在七牛云对象存储空间中的url
        String url =  domain+ key +"?attname="+file.getOriginalFilename();
        sourceMaterial.setId(key);
        sourceMaterial.setAddress(url);
        String id = sourceMaterialService.checkSource(key,conferenceId);
        if (id != null) {
            return new Result<>().setCode(403).setMessage("重复上传");
        }
        sourceMaterialService.save(sourceMaterial,file);
        HashMap map = new HashMap<>();
        map.put("url",url);
        map.put("fileName",file.getOriginalFilename());
        return new Result<>().setCode(200).setMessage("上传成功").setData(map);
    }


    @PostMapping("chunkUpload")
    @ApiOperation("分片上传")
    @OperLog(operModule = "数据管理模块",operType = "post",operDesc = "分片上传素材操作")
    public Result fileChunkUpload(MultipartFileParam multipartFileParam,
                                HttpServletResponse response,
                                HttpServletRequest request,
                                @RequestParam(value = "auther",required = false) String auther,
                                @RequestParam(value = "conferenceId",required = false) Integer conferenceId) throws IOException {
        if (multipartFileParam.getFile() == null) {
            return new Result<>().setCode(204).setMessage("请上传文件");
        }
        String url =  sourceMaterialService.chunkUpload(multipartFileParam,response,request,auther,conferenceId);
        if ("false".equals(url)) {
            return new Result<>().setCode(500).setMessage("上传失败,请重新上传");
        }else if ("true".equals(url)) {
            return new Result<>().setCode(200).setMessage("分片上传成功!");
        }else {
            HashMap map = new HashMap<>();
            map.put("url",url);
            map.put("fileName",multipartFileParam.getFileName());
            return new Result<>().setCode(200).setMessage("文件上传成功").setData(map);
        }
    }

    @GetMapping("getVeideoSourse")
    @RequiresPermissions("datamanage:find:multimediadata")
    @ApiOperation("获取多媒体资源信息")
    @OperLog(operModule = "数据管理模块",operType = "get",operDesc = "获取多媒体素材信息操作")
    public Result getVideoSource(@RequestParam(required = false) String id,
                                 @RequestParam Integer pageSize,
                                 @RequestParam Integer pageNum) {
        HashMap map = new HashMap<>();
        map.put("id",id);
        PageHelper.startPage(pageNum, pageSize);
        List<SourceMaterial> list = sourceMaterialService.selectVedioSourceMaterialByName(map);
        return new Result<>().setCode(200).setMessage("操作成功").setData(new PageInfo<>(list));
    }

    @GetMapping("getPreviewConferenceData")
    @ApiOperation("获取历史会议数据")
    @RequiresPermissions("datamanage:find:historymeeting")
    @OperLog(operModule = "数据管理模块",operType = "get",operDesc = "获取历史会议数据")
    public Result getPreviewConferenceData(@RequestParam("pageSize") Integer pageSize,
                                           @RequestParam("pageNum") Integer pageNum,
                                           @RequestParam(value = "name", required = false) String name,
                                           HttpServletRequest request) {
        String account = TokenUtil.getTokenName(request);
        PageHelper.startPage(pageNum,pageSize);
        return new Result<>().setCode(200).setMessage("查看历史会议数据成功").setData(new PageInfo<>(sourceMaterialService.getPreviewData(account,name)));
    }


    @PostMapping("localChunkUploadTest")
    @ApiOperation("本地多媒体资源上传（测试）")
    @OperLog(operModule = "数据管理模块",operType = "post",operDesc = "本地上传多媒体测试操作")
    public String uploadlocalVideoSource() {
        String realPath = "D:\\Users\\29989\\MobileFile\\南山南.mp4";
        String name = "南山南.mp4";
        String key = QiNiuUtils.localChunkUpload(realPath,name);
        String domain = "http://skylery.walnute.top/";
        String url =  domain+ key +"?attname="+name;

        SourceMaterial sourceMaterial = new SourceMaterial();
        sourceMaterial.setId(key);
        sourceMaterial.setSource("本地上传");
        sourceMaterial.setName(name);
        sourceMaterial.setImportTime(new Date());
        sourceMaterial.setImportPeople("lisi");
        sourceMaterial.setAddress(url);
        if (sourceMaterialService.saveVideoSource(sourceMaterial)) {
            return "success";
        }
        return "false";
    }




}
